package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.page.BasePageFactory;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.GopUser;
import com.zsk.shop.entity.ShopAppVersion;
import com.zsk.shop.enums.EnumLoginPlatform;
import com.zsk.shop.mapper.ShopAppVersionMapper;
import com.zsk.shop.model.params.AddShopAppVersionParams;
import com.zsk.shop.model.params.EditShopAppVersionParams;
import com.zsk.shop.model.params.GopShopAppVersionListParams;
import com.zsk.shop.model.results.GopShopAppVersionListResult;
import com.zsk.shop.model.results.ShopAppVersionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopAppVersionService extends ServiceImpl<ShopAppVersionMapper, ShopAppVersion> {

    @Autowired
    private GopUserService gopUserService;

    public BaseResponse<ShopAppVersionResult> check(Long versionCode, String versionNumber, Integer platform) {
        //找到比当前版本号更高的且有强制升级的版本，如果有返回该数据，如果没有返回空
        LambdaQueryWrapper<ShopAppVersion> queryWrapper = new LambdaQueryWrapper<>();
        if(platform.equals(1)){
            queryWrapper.gt(ShopAppVersion::getVersionNumber, versionNumber);
        }else if(platform.equals(2)){
            queryWrapper.gt(ShopAppVersion::getVersionCode, versionCode);
        }
        queryWrapper.eq(ShopAppVersion::getIsDeleted, false);
//        queryWrapper.eq(YlAppVersion::getForcedUpgrade, true);
        queryWrapper.eq(ShopAppVersion::getIsPublish, true);
        queryWrapper.eq(ShopAppVersion::getVersionPlatform, platform);
        queryWrapper.orderByDesc(ShopAppVersion::getVersionNumber);
        queryWrapper.last("limit 1");
        ShopAppVersion ylAppVersion = this.getOne(queryWrapper);
        if (ToolUtil.isNotEmpty(ylAppVersion)) {
            return BaseResponse.success(EntityConvertUtils.convertAToB(ylAppVersion, ShopAppVersionResult.class));
        }
        return BaseResponse.success();
    }

    public BaseResponse<GopShopAppVersionListResult> GopYlAppVersionList(GopShopAppVersionListParams params) {
        Page pageContext = BasePageFactory.defaultPage();
        LambdaQueryWrapper<ShopAppVersion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopAppVersion::getIsDeleted, false);
        if (ToolUtil.isNotEmpty(params.getKey())) {
            queryWrapper.and(x -> x.like(ShopAppVersion::getVersionName, params.getKey()).or().like(ShopAppVersion::getVersionNumber, params.getKey()));
        }
        if (ToolUtil.isNotEmpty(params.getIsPublish())) {
            queryWrapper.eq(ShopAppVersion::getIsPublish, ToolUtil.parseBoolean(params.getIsPublish()));
        }
        if (ToolUtil.isNotEmpty(params.getPlatform())) {
            queryWrapper.eq(ShopAppVersion::getVersionPlatform, Integer.parseInt(params.getPlatform()));
        }
        queryWrapper.orderByDesc(ShopAppVersion::getId);
        IPage page = this.page(pageContext, queryWrapper);
        List<GopShopAppVersionListResult> results = EntityConvertUtils.convertAListToBList(page.getRecords(), GopShopAppVersionListResult.class);
        List<Long> userIds = results.stream().map(GopShopAppVersionListResult::getCreateUser).distinct().collect(Collectors.toList());
        List<GopUser> gopUserList = gopUserService.queryNameByIds(userIds);
        int key = 1;
        for (GopShopAppVersionListResult result : results) {
            GopUser gopUser = gopUserList.stream().filter(x -> x.getId().equals(result.getCreateUser())).findFirst().orElse(new GopUser());
            result.setCreateUserStr(gopUser.getName());
            result.setVersionPlatformStr(EnumLoginPlatform.getNameByCode(result.getVersionPlatform()));
            result.setKey(key);
            key++;
        }
        page.setRecords(results);
        return BasePageFactory.createPageInfo(page);
    }

    public BaseResponse changePublishById(Long id, Boolean toPublish) {
        ShopAppVersion ylAppVersion = this.getById(id);
        ylAppVersion.setIsPublish(toPublish);
        ylAppVersion.setUpdateTime(new Date());
        ylAppVersion.setUpdateUser(HttpContext.getUserId());
        if(toPublish){
            updateIsPublish(ylAppVersion.getVersionPlatform());
        }
        return BaseResponse.success(this.saveOrUpdate(ylAppVersion));
    }

    @Transactional(rollbackFor = {Exception.class})
    public BaseResponse addAppVersion(AddShopAppVersionParams params) {
        if (ToolUtil.isOneEmpty(params, params.getVersionName(), params.getVersionNumber(), params.getVersionPlatform(),
                params.getForcedUpgrade())) {
            return BaseResponse.error("必填参数缺失");
        }
        if (params.getVersionPlatform().equals(EnumLoginPlatform.ANDROID.getCode())) {
            if (ToolUtil.isEmpty(params.getUrl())) {
                return BaseResponse.error("缺少APK包地址");
            }
        }
        ShopAppVersion appVersion = ShopAppVersion.builder()
                .versionName(params.getVersionName()).versionPlatform(params.getVersionPlatform()).versionCode(params.getVersionCode())
                .versionNumber(params.getVersionNumber()).forcedUpgrade(params.getForcedUpgrade()).url(params.getUrl())
                .tip(params.getTip()).isDeleted(false).isPublish(false).createTime(new Date()).createUser(HttpContext.getUserId())
                .build();
        this.save(appVersion);
        return BaseResponse.success("新增成功");
    }

    public void updateIsPublish(Integer versionPlatform){
        LambdaUpdateWrapper<ShopAppVersion> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopAppVersion::getVersionPlatform, versionPlatform);
        updateWrapper.set(ShopAppVersion::getIsDeleted, true);
        updateWrapper.eq(ShopAppVersion::getIsPublish, true);
        updateWrapper.eq(ShopAppVersion::getVersionPlatform, versionPlatform);
        update(updateWrapper);
    }

    public BaseResponse editAppVersion(EditShopAppVersionParams params) {
        if (ToolUtil.isOneEmpty(params, params.getId())) {
            return BaseResponse.error("当前id有误");
        }
        ShopAppVersion oldEntity = getOldEntity(params);
        if (ToolUtil.isEmpty(oldEntity)) {
            return BaseResponse.error("未找到当前版本内容,修改失败");
        }
        ShopAppVersion newEntity = getEntity(params);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateTime(new Date());
        newEntity.setUpdateUser(HttpContext.getUserId());
        this.updateById(newEntity);
        return BaseResponse.success("修改成功");
    }

    private ShopAppVersion getOldEntity(EditShopAppVersionParams param) {
        return this.getById(param.getId());
    }

    private ShopAppVersion getEntity(EditShopAppVersionParams param) {
        param = EntityConvertUtils.setNullValue(param);
        ShopAppVersion entity = EntityConvertUtils.convertAToB(param, ShopAppVersion.class);
        return entity;
    }

    public BaseResponse deleteById(Long id) {
        ShopAppVersion appVersion = this.getById(id);
        appVersion.setIsDeleted(true);
        appVersion.setUpdateUser(HttpContext.getUserId());
        appVersion.setUpdateTime(new Date());
        this.updateById(appVersion);
        return BaseResponse.success("删除版本成功");
    }
}
